<?php
/**
 * The controller for User Information.
 *
 */
require_once(APP.'libs'.DS.'util.php');
require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'php-excel.class.php');
App::import('Vendor','/infolex/rest_wrapper');
class ProductController extends AppController
{
	var $helpers = array('javascript','ToolTip');
	var $layout='';
	var $uses=array('User','Product','Clicklogs','Change');
	var $components=array('Account','Upload');

	// 免费免费产品列表~~~~需要添加逻辑
	function getProductList($curPage=1,$isCharge=0,$time=null,$lastNew=0,$cat = -9999)
	{
	    $isCharge = 0;
	    $curPage = intval($curPage);
	    $time = intval($time);
	    $lastNew = intval($lastNew);
	    $cat = !isset($_REQUEST['cat'])?intval($cat):intval($_REQUEST['cat']);
	    $this->set("curPage",$curPage);
	    $this->set("isCharge",$isCharge);
	    $this->set("time",intval($time));
	    $this->set("lastNew",$lastNew);
	    $this->set("cat",$cat);
	    
		$this->__getProduct($curPage, 0, $lastNew, $cat);
		$this->render(null,'management_layout','/product/product_free_list');
		return;		
	}
	
	/*
	*
	*分页查询产品列表
	* 参数curPage为当前页
	* 参数isCharge 是否收费 默认为0 免费
	*/

	function __getProduct($curPage,$isCharge,$lastNew = 0, $cat = -9999){
	    uses('sanitize');
	    $q = empty($_REQUEST['q'])?'':trim($_REQUEST['q']);
	    $sanitize=new Sanitize();
	    $q = $sanitize->escape(strip_tags($q));
	    
	    if (!empty($q)) {
		    $sql = "g_price=0 and `g_name` LIKE '%{$q}%'";
		    $count = 10;
		} else {
   			$sql="g_price=0";
   			if ($cat!=-9999 ) {
   			    $sql .= ' and g_cat='.intval($cat);
   			}
   			$count=$this->Product->findCount($sql);

		}

		if ($lastNew){
			$count = SystemProperties::$product_pageNumber - 1;
		}
		if($count==0){
			$this->set("productList",null);
			$this->set("curPage",0);
			$this->set("totalPage",0);
			return;
		}
		$number=SystemProperties::$product_pageNumber;
		$page=intval($count/$number);
		if($count%$number!=0){
			$page+=1;
		}
		if($curPage>$page){
			$curPage=$page;
		}else if($curPage<=0){
			$curPage=1;
		}
		$prenum=($curPage-1)*$number;
		
		if ($lastNew){
			$this->set("productList",$this->Product->selectProductInfoLast($prenum,$sql));
			$this->set("lastNew",1);
		}else {
			$this->set("productList",$this->Product->selectProductInfo($prenum,$sql));	
			$this->set("lastNew",0);
		}
		$this->set("curPage",$curPage);
		$this->set("totalPage",$page);
		$this->set("q",$q);
	}


	function updateProductInList($pid = 0,$in_list = 0,$page=1,$isCharge=0){
		$ids='';
		if (empty($pid)){
			echo 'Error Set Product。';
			exit();
		}

		$this->Product->updateProductInList($pid,$in_list);
		$this->redirect(SystemProperties::$app_host."/Product/getProductList/{$page}/{$isCharge}/".time());
	}

	/*
	* 删除产品
	*/
	function deletePruduct($isCharge=0){
		$ids='';
		if(!empty($this->data)){
			foreach($this->data as $key=>$value){//$key 对应产品的id value=1表示是要删除的
				if($value==1){
					$ids.=$key.",";
				}
			}
			$ids=substr($ids,0,-1);
			if(!empty($ids)){
				$data=$this->Product->selectMoreProduct($ids);
				foreach($data as $key=>$product){
					for($i=0;$i<6;$i++){
						$imgkey=SystemProperties::$img_names[$i];
						if(!empty($product['g_products'][$imgkey])){
							$this->Upload->removePhoto($product['g_products'][$imgkey]);
						}
					}
				}
				$this->Product->deleteProduct($ids);
			}
		}
		if($isCharge==0){
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/0/".time());
		}else{
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/1/".time());
			return;
		}
	}
	/*
	* 点击修改产品链接跳转到修改产品页面
	*/
	function modifyPruduct($isCharge=0,$id=null){
		if($isCharge==0){
			$this->set("product_action","/product/add");
			if(!empty($id)){
				$data=$this->Product->selectProduct($id);
				$this->data=$data[0];
				$this->set("product_action","/product/modify");
			}
		}else{
			$this->set("product_action","/product/add/1");
			if(!empty($id)){
				$data=$this->Product->selectProduct($id);
				$this->data=$data[0];
				$this->set("product_action","/product/modify/1");
			}
		}

		if($isCharge==0){
			if(!empty($id)){
				$this->set("product_title","修改免费试用产品");
			}else{
				$this->set("product_title","添加免费试用产品");
			}
			$this->render(null,'management_layout','/product/product_modify');
			return;
		}else{
			if(!empty($id)){
				$this->set("product_title","修改半价试用产品");
			}else{
				$this->set("product_title","添加半价试用产品");
			}
			$this->render(null,'management_layout','/product/product_modify_charge');
			return;
		}
	}
	/*
	* 修改产品
	*/
	function modify($isCharge=0){
		uses('sanitize');
		$sanitize=new Sanitize();
		$id=$this->data['g_products']['g_id'];
		if(empty($this->data['g_products']['g_name'])){
			$name='';
		}else{
			$name=$sanitize->escape($this->data['g_products']['g_name']);
		}
		if(empty($this->data['g_products']['g_brand'])){
			$g_brand='';
		}else{
			$g_brand=$sanitize->escape($this->data['g_products']['g_brand']);
		}
		if(empty($this->data['g_products']['g_jiazhi'])){
			$g_jiazhi=0;
		}else{
			$g_jiazhi=$sanitize->escape($this->data['g_products']['g_jiazhi']);
		}
		if(empty($this->data['g_products']['only_apply_once'])){
			$only_apply_once=0;
		}else{
			$only_apply_once=1;
		}		
		if(empty($this->data['g_products']['g_hot'])){
			$g_hot=0;
		}else if(intval($this->data['g_products']['g_hot'])!=0 ){
			$g_hot=1;
		}else{
			$g_hot=0;
		}
		//if($isCharge!=0){
		if(empty($this->data['g_products']['g_timesplit'])){
			$g_timesplit=0;
		}else{
			$g_timesplit=$sanitize->escape($this->data['g_products']['g_timesplit']);
		}
	    if(empty($this->data['g_products']['g_cat'])){
			$g_cat=0;
		}else{
			$g_cat=intval($sanitize->escape($this->data['g_products']['g_cat']));
		}		
		
		//if($isCharge!=0){
		echo $this->data['g_products']['g_timestart'];

		if(empty($this->data['g_products']['g_timestart'])){
			$g_timestart=date('Y-m-d H:i:s');
		}else{
			$g_t=strtotime($sanitize->escape($this->data['g_products']['g_timestart']));
			if ($g_t > time()){
				$g_timestart=date('Y-m-d H:i:s');
			}else {
				$g_timestart=date('Y-m-d H:i:s',$g_t);
			}
		}
		$num_per_time=0; 
		//		if (SystemProperties::$platform=='renren') {
		//			if(empty($this->data['g_products']['num_per_time'])){
		//				$num_per_time=0;
		//			}else{
		//				$num_per_time=intval($sanitize->escape($this->data['g_products']['num_per_time']));
		//			}
		//		}
		if(empty($this->data['g_products']['g_lucknum'])){
			$g_lucknum=0;
		}else{
			$g_lucknum=$sanitize->escape($this->data['g_products']['g_lucknum']);
		}		//}
		$g_price=0;
		if(empty($this->data['g_products']['g_number'])){
			$g_number=0;
		}else{
			$g_number=$sanitize->escape($this->data['g_products']['g_number']);
		}
		
		// -1 特殊
		if ($g_cat == -1) {
		    $num_per_time = 0;
		    $g_number = 0;		    
		}
		//		if (SystemProperties::$platform=='renren'){
		//		    if ($num_per_time == 0 ) {
		//		        $g_number = 0 ;
		//		    } elseif (intval($g_number) <= 0 || intval($g_number)<intval($num_per_time)){
		//				echo '库存不能直接设置为0，并且至少要达到当期赠送数量'.$num_per_time.'。  如果要修改的是已隐藏的产品,请同时设置库存和赠送数为0。 ';
		//				exit();
		//			}
		//		}
		if(empty($this->data['g_products']['g_description'])){
			$g_description='';
		}else{
			$g_description=$sanitize->escape($this->data['g_products']['g_description']);
		}
		if(empty($this->data['g_products']['popularity'])){
			$popularity=0;
		}else{
			$popularity=$sanitize->escape($this->data['g_products']['popularity']);
		}
		if(empty($this->data['g_products']['rand'])){
			$rand=0;
		}else{
			$rand=$sanitize->escape($this->data['g_products']['rand']);
		}
		if(empty($this->data['g_products']['g_protal_url'])){
			$g_protal_url='';
		}else{
			$g_protal_url=$sanitize->escape($this->data['g_products']['g_protal_url']);
		}
		if(empty($this->data['g_products']['g_extra_url'])){
			$g_extra_url='';
		}else{
			$g_extra_url=$sanitize->escape($this->data['g_products']['g_extra_url']);
		}		
		if(empty($this->data['g_products']['feed_word'])){
			$feed_word='';
		}else{
			$feed_word=$sanitize->escape($this->data['g_products']['feed_word']);
		}
		if(empty($this->data['g_products']['feed_word_title'])){
			$feed_word_title='';
		}else{
			$feed_word_title=$sanitize->escape($this->data['g_products']['feed_word_title']);
		}		
		if(empty($this->data['g_products']['g_address'])){
			$g_address='';
		}else{
			$g_address=$sanitize->escape($this->data['g_products']['g_address']);
		}
		if(empty($this->data['g_products']['g_special_html'])){
			$g_special_html='';
		}else{
			$g_special_html=$sanitize->escape($this->data['g_products']['g_special_html']);
		}
		if(empty($this->data['g_products']['g_notice_html'])){
			$g_notice_html='';
		}else{
			$g_notice_html=$sanitize->escape($this->data['g_products']['g_notice_html']);
		}		
		if(empty($this->data['g_products']['is_ad_link'])){
			$is_ad_link=0;
		}else{
			$is_ad_link=1;
		}
		if(empty($this->data['g_products']['in_wangqi_list'])){
			$in_wangqi_list=0;
		}else{
			$in_wangqi_list=1;
		}		
		
		
		if($this->data['g_products']['type'] == 'coupon') {
			$is_coupon_show=1;
			$g_number = 9999;
			$g_timesplit = 9999000;
			$g_lucknum = -1;
		} else {
			$is_coupon_show=0;
		}
		$sql='';
		for($i=0;$i<6;$i++){
			$img="g_img".$i;
			if(!empty($this->data['g_products'][$img]['name'])){
				$info = $this->data['g_products'][$img];
				$imgkey=SystemProperties::$img_names[$i];
				$target_name = time().$i.md5($info['name']);
				$target_name = $this->Upload->uploadPhoto($info,$target_name);
				$sql.="$imgkey='$target_name',";

			}
		}
		//if($isCharge!=0){
		$g_price = intval($g_price);
		$g_timesplit = intval($g_timesplit);
		$g_lucknum = intval($g_lucknum);
//		if (SystemProperties::$platform=='renren') {
//		    $sql.="num_per_time=$num_per_time,";
//		}
		$sql.="feed_word='$feed_word',feed_word_title='$feed_word_title',";
		$sql.="g_extra_url='$g_extra_url',only_apply_once=$only_apply_once,g_timesplit=$g_timesplit,g_lucknum=$g_lucknum,g_timestart='$g_timestart',is_ad_link={$is_ad_link},is_coupon_show={$is_coupon_show},";
		//}
		$sql.="in_wangqi_list=$in_wangqi_list,g_cat=$g_cat,g_price=$g_price,g_name='$name',g_brand='$g_brand',g_jiazhi=$g_jiazhi,g_number=$g_number,g_description='$g_description',popularity=$popularity,rand=$rand,g_hot=$g_hot,g_protal_url='$g_protal_url',g_address='$g_address',g_special_html='$g_special_html',g_notice_html='$g_notice_html'";
		$this->Product->updateProduct($id,$sql);
		if($isCharge==0){
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/0/".time());
		}else{
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/1/".time());
			return;
		}
	}
	/*
	* 添加产品  每次修改数据库后 一定要清空缓存表！！
	*/
	function add($isCharge=0){
		if(empty($this->data['g_products']['g_id'])){
			unset($this->data['g_products']['g_id']);
		}
		for($i=0;$i<6;$i++){
			$img="g_img".$i;
			if(!empty($this->data['g_products'][$img]['name'])){
				$info = $this->data['g_products'][$img];
				$imgkey=SystemProperties::$img_names[$i];
				$target_name = time().$i.md5($info['name']);
				$target_name = $this->Upload->uploadPhoto($info,$target_name);
				$this->data['g_products'][$imgkey] = $target_name;

			}
		}

		if(empty($this->data['g_products']['g_jiazhi'])){
			$this->data['g_products']['g_jiazhi']=0;
		}
		if(empty($this->data['g_products']['g_number'])){
			$this->data['g_products']['g_number']=0;
		}
		if(empty($this->data['g_products']['popularity'])){
			$this->data['g_products']['popularity']=0;
		}
		if(empty($this->data['g_products']['g_hot'])){
			$this->data['g_products']['g_hot']=0;
		}
		if(empty($this->data['g_products']['rand'])){
			$this->data['g_products']['rand']=0;
		}
		if(empty($this->data['g_products']['type'])){
			$this->data['g_products']['type']='kuaidi';
		}		
		if(empty($this->data['g_products']['g_lucknum'])){
			$this->data['g_products']['g_lucknum']=0;
		}
		//当前时间 作为start 不可以修改
		$this->data['g_products']['g_timestart']=date('Y-m-d H:i:s');
		if(empty($this->data['g_products']['g_timesplit'])){
			$this->data['g_products']['g_timesplit']=0;
		}
		$this->data['g_products']['g_price']=0;
		if(empty($this->data['g_products']['is_ad_link'])){
			$this->data['g_products']['is_ad_link']=0;
		}		
		if(empty($this->data['g_products']['is_coupon_show'])){
			$this->data['g_products']['is_coupon_show']=0;
		}	
		if ($this->data['g_products']['is_coupon_show']!=0 ||$this->data['g_products']['type']=='coupon') {
		    $this->data['g_products']['is_coupon_show'] = 1;
		    $this->data['g_products']['type']='coupon';
		    $this->data['g_products']['g_timesplit'] = 9999000;
		    $this->data['g_products']['g_number'] = 9999;
		    $this->data['g_products']['g_lucknum'] = -1;
		}
			
		$this->data['g_products']['g_cat']=intval($this->data['g_products']['g_cat']);
		$this->Product->save($this->data['g_products'],false);
		if($isCharge==0){
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/0/".time());
		}else{
			$this->redirect(SystemProperties::$app_host."/Product/getProductList/1/1/".time());
			return;
		}
	}

    function cloneProduct($pid) {
        $pid = intval($pid);
        $this->Product->cloneProduct($pid);
        $this->redirect(SystemProperties::$app_host."/product/getProductList/1/0/0/1".time());
    }
    function deletePhoto($pid, $picid) {
        $pid = intval($pid);
        $picid = intval($picid);
        $this->Product->deletePhoto($pid, $picid);  
        exit()      ;
    }
    function showMyProductList(){
		if (empty($_SESSION['guest_user_id'])){
			echo '404';
			exit();
		}
		$datas = array();
		if (!empty($_SESSION['guest_user_pids'])){
			foreach ($_SESSION['guest_user_pids'] as $pid){
				$datas[] = $this->Product->selectProduct($pid);
			}
		}
		$this->set("data",$datas);
		$this->render('/product/product_guest_product_list');
	}
	function showClickLogs($pid,$page = 1,$export_excel = 0){
		if (empty($_SESSION['admin_user_id'])){
			if (empty($_SESSION['guest_user_id'])){
				echo '404';
				exit();
			}else {
				// guest
				if (!in_array($pid,$_SESSION['guest_user_pids'])){
					//不能察看此商品 //返回
					$this->redirect(SystemProperties::$app_host."/Product/showMyProductList/");
					return;
					;
				}
			}
		}

		if ($export_excel==1){
			$data= $this->__get_click_logs($pid,0,10000000);
			$xls = new Excel_XML('UTF-8', false, 'ClickLOG-'.$pid.'-'.SystemProperties::$platform);
			foreach ($data as $da){
				if (!empty( $da['g_clicklogs']['extra'])){
					$list = explode('|',$da['g_clicklogs']['extra']);
					$list_info = join(',',$list);
				}else {
					$list_info = '-';
				}

				$xls->addArray(array(array(
				$da['g_users']['g_uid'],
				$da['g_users']['g_name'].(empty($da['g_users']['g_realname'])?'':"({$da['g_users']['g_realname']})"),
				$da['g_clicklogs']['time'],
				empty($da['g_users']['g_realname'])?'-':($da['g_users']['g_sex']==0?'女':'男'),
				empty($da['g_users']['g_realname'])?'-':(date('Y')-date('Y',strtotime($da['g_users']['g_birthday']))+1),
				$da['g_users']['g_province'].$da['g_users']['g_city'],
				urldecode(urldecode($list_info))
				)));
			}
			$xls->generateXML('ClickLog'.$pid.'-'.SystemProperties::$platform);
			exit();
		}
		$count = 100;
		if (empty($page)){
			$page = 1;
		}
		$start = ($page-1)*$count;

		$product_data = $this->Product->selectProduct($pid);
		$total = $this->Clicklogs->getLogCount($pid);
		$data = $this->__get_click_logs($pid,$start,$count);
		$this->set("data",$data);
		$this->set("page",$page);
		$this->set("pagesize",$count);
		$this->set("product_data",$product_data);
		$this->set("total",$total);
		$this->render('/product/product_click_logs');
	}
	function __get_click_logs($pid,$start,$count){
		return $this->Clicklogs->getLog($pid,$start,$count);
	}


	function saveExcelClickLog(){
	    if (empty($_REQUEST['from']) || empty($_REQUEST['end'])) {
	        $this->set("action",'/product/saveExcelClickLog');
	        $this->set("name",'下载点击详情'.'Excel表格：');
	        $this->render(null,'management_layout','/product/select_time_range_download');
	        return ;
	    } else {
	        if (strstr($_REQUEST['from'],'-')) {
	            $_REQUEST['from'] = strtotime($_REQUEST['from']);
	            $_REQUEST['end'] = strtotime($_REQUEST['end'].'+1day');
	        }
	    }
	    
		ini_set("memory_limit","2048M");
		$data = $this->Clicklogs->getLogAll(0,100000000);
		$xls = new Excel_XML('UTF-8', false, 'Click'.SystemProperties::$platform);
		$xls->addArray(array(array(
		//'序号',
		'点击',
		'用户ID',
		//'用户名称',
		'产品ID',
		//'产品名称',
		)));
		foreach ($data as $r){
			$xls->addArray(array(array(
			//$r['g_clicklogs']['seqid'],
			$r['g_clicklogs']['time'],
			$r['g_users']['g_uid'],
			//$r['g_users']['g_name'],
			$r['g_products']['g_id'],
			//$r['g_products']['g_name']
			)));
		}
		$time_start = empty($_REQUEST['from'])?0:intval($_REQUEST['from']);
		if (!empty($time_start)){
		    $str = date('Y-m',$time_start);
		}
		$from_str = date('Y-m-d',$_REQUEST['from']);
		$end_str = date('Y-m-d',$_REQUEST['end']-1);
		$xls->generateXML(SystemProperties::$platform."_TotalClick_{$from_str}_to_{$end_str}");
		exit();
	}
	function saveExcelLog($type=0){
	    
	    if (empty($_REQUEST['from']) || empty($_REQUEST['end'])) {
	        $this->set("action",'/product/saveExcelLog/'.$type);
	        $this->set("name",'下载'.($type==0?'积分兑换':'成功申请').'Excel表格：');
	        $this->render(null,'management_layout','/product/select_time_range_download');
	        return ;
	    } else {
	        if (strstr($_REQUEST['from'],'-')) {
	            $_REQUEST['from'] = strtotime($_REQUEST['from']);
	            $_REQUEST['end'] = strtotime($_REQUEST['end'].'+1day');
	        }
	    }
	    
		if ($type == 0){
			$data=$this->User->listChangeOK(1,100000000);
		}else {
			$data=$this->User->listApplyOK(1,100000000);
		}
		$xls = new Excel_XML('UTF-8', false, ($type==0?'Exchange':'Apply').SystemProperties::$platform);
		$xls->addArray(array(array(
		'时间',
		'ID',
		'产品',
		'用户付费',
		'用户ID',
		'用户名',
		'真实姓名',
		'性别',
		'年龄',
		'地区',
		'快递费',
		'手机',
		'邮箱',
		'地址',
		'邮编',
		'提取邮编',
		)));
		foreach ($data as $da){
			if (empty($da['g_products'])){
				$da['g_products'] = $da['g_changes'];
			}
			
			if (preg_match('/\b(\d{6})\b/', $da['g_users']['g_address'], $matches)>0){
				$draw_zipcode = $matches[1];
			} else {
				$draw_zipcode = '';
			}
			$xls->addArray(array(array(
			empty($da['g_apply0']['g_time'])?$da['g_exchange0']['g_time']:$da['g_apply0']['g_time'],
			$da['g_products']['g_id'],
			$da['g_products']['g_name'],
			$da['g_products']['g_price'],
			$da['g_users']['g_uid'],
			$da['g_users']['g_name'],
			$da['g_users']['g_realname'],
			($da['g_users']['g_sex']==0?'女':'男'),
			date('Y')-date('Y',strtotime($da['g_users']['g_birthday']))+1,
			$da['g_users']['g_province'].$da['g_users']['g_city'],
			empty($da['g_users']['g_kuaidi'])?'-':($da['g_users']['g_kuaidi']=='daofu'?'到付':'淘宝'),
			$da['g_users']['g_phone'],
			$da['g_users']['g_mail'],
			$da['g_users']['g_address'],
			$da['g_users']['g_zipcode'],
			$draw_zipcode,
			)));

		}
		$from_str = date('Y-m-d',$_REQUEST['from']);
		$end_str = date('Y-m-d',$_REQUEST['end']-1);
		$xls->generateXML(SystemProperties::$platform.($type==0?'_Exchange':'_Apply')."_{$from_str}_to_{$end_str}");
		exit();

	}
	function saveExcelApplyLog(){
		$data=$this->User->listApplyOK(1,100000000);
		$xls = new Excel_XML('UTF-8', false, 'Apply'.SystemProperties::$platform);
		foreach ($data as $r){
			$xls->addArray(array(array(
			//$r['g_clicklogs']['seqid'],
			$r['g_clicklogs']['time'],
			$r['g_users']['g_uid'],
			//$r['g_users']['g_name'],
			$r['g_products']['g_id'],
			//$r['g_products']['g_name']
			)));
		}
		$xls->generateXML('Apply'.SystemProperties::$platform);
		exit();
	}
	function coupon($pid, $type = 0, $order = 'id', $p = 1) {
	    
	    //$type : 0 all   1 unuse  2 used
	    $type = intval($type);
	    $order = empty($order)?'id':trim($order);
	    $pid = intval($pid);
	    $n = 30;
	    if ($p<=0) {
	        $p =1;
	    }

	    if ($pid > 100000) {
	       $info = $this->Change->selectProduct($pid - 100000); 
	    } else {
	       $info = $this->Product->selectProduct($pid);
	    }
	    if (empty($info) || 
	           ($info[0]['g_products']['is_coupon_show']!=1 && $info[0]['g_changes']['is_coupon_show']!=1)
	           ) {
	        header("Content-type: text/html; charset=utf-8"); 
	        echo '<script> alert("产品不存在，或者产品不是优惠码发放产品。");history.go(-1);</script>';
	        exit();
	    }
	    
	    $list = $this->Product->getCouponList($pid, $type, $order, $p-1, $n, $total);
	    $pageNumber = ceil($total/$n);
        $pager = Util::make_pager($total, $n, $p,SystemProperties::$app_host.'/product/coupon/'."$pid/$type/$order");
	    $this->set("list", $list);
	    $this->set("pid", $pid);
	    $this->set("p", $p);
	    $this->set("total", $total);
	    $this->set("pager", $pager);
	    $this->set("info", empty($info[0]['g_products'])?$info[0]['g_changes']:$info[0]['g_products']);
	    
    	$this->render(null,'management_layout','/coupon/listcoupon');
	}
	function deleteCoupon($pid, $coupon_id) {
   	    echo '<b>请稍等...</b>';

	    $pid = intval($pid);
	    $coupon_id = intval($coupon_id);
	    $data = $this->Product->deleteCoupon($pid, $coupon_id);
	    echo '<script>location.reload();</script>';
	    exit();
	}
	function addCoupon($pid) {
	    if (empty($pid) || empty($_REQUEST['list'])) {
	        return ;
	    }
	    $list = explode(chr(10),$_REQUEST['list']);
	    $time = date('Y-m-d',strtotime($_REQUEST['time']));
	    $data = $this->Product->addCoupon($pid, $list, $time);
	    $this->redirect(SystemProperties::$app_host."/Product/coupon/$pid/?".time());
	}

	// no need to login
	function captcha($token){
		if (empty($token)){
			echo "Token为空，您无权访问";
			exit;
		}
		$product_kw = empty($_GET['product_kw'])? null: trim($_GET['product_kw']);
		if ($product_kw && @iconv('utf-8', 'utf-8', $product_kw) != $product_kw){
			$product_kw = iconv('gb2312', 'utf-8', $product_kw);
		}
		if (!$this->getOrcheckCaptchaUrl($product_kw, $token)){
			echo "验证失败，您无权访问";
			exit;
		}

		$this->set('isAdmin', false);

		$this->_captchaAction();
	}
	// need login
	function adminCaptcha(){
		$this->set('isAdmin', true);
		$this->_captchaAction();
	}
	function _captchaAction(){/*{{{*/
		$download = empty($_REQUEST['download'])? 0: 1; 

		$platform = empty($_REQUEST['platform'])? 'sina': trim($_REQUEST['platform']);
		$page = empty($_REQUEST['page'])? 1: intval($_REQUEST['page']);
		$per_page = 30;
		if ($download){
			$page = 1;
			$per_page = 100000; // max
		}
		
		$product_kw = empty($_GET['product_kw'])? null: trim($_GET['product_kw']);
		$status = empty($_GET['status'])? null: trim($_GET['status']);
		$user_name = empty($_GET['user_name'])? null: trim($_GET['user_name']);
		$code = empty($_GET['code'])? null: trim($_GET['code']);
		$time_type = empty($_GET['time_type'])? 'create': trim($_GET['time_type']);
		$start_time = empty($_GET['start_time'])? date("Y-m-d H:i:s", strtotime("-1 months")): date("Y-m-d H:i:s", strtotime($_GET['start_time']));
		$end_time = empty($_GET['end_time'])? date("Y-m-d H:i:s"): date("Y-m-d H:i:s", strtotime($_GET['end_time']));

		//var_dump($product_kw, $status, $user_name, $code, $time_type, $start_time, $end_time);

		if ($product_kw && @iconv('utf-8', 'utf-8', $product_kw) != $product_kw){
			$product_kw = iconv('gb2312', 'utf-8', $product_kw);
		}
		if ($user_name && @iconv('utf-8', 'utf-8', $user_name) != $user_name){
			$user_name = iconv('gb2312', 'utf-8', $user_name);
		}

		$this->set('unlogin_url', $this->getOrcheckCaptchaUrl($product_kw));
		$this->set('check_url', $this->getSmallCaptchaUrl($product_kw));
		$this->set('download_url', $this->make_page_url_prefix('http://'.$_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI']).'&download=1'); 

		$status_select = array(
			array('v' => '', 'text' => '全部'),
			array('v' => 'active', 'text' => '未领取'),
			array('v' => 'used', 'text' => '已领取'),
		);
		$time_type_select = array(
			array('v' => 'create', 'text' => '中奖时间'),
			array('v' => 'apply', 'text' => '领奖时间'),
		);
		$platform_select = array(
			array('v' => 'sina', 'text' => '新浪'),
			array('v' => 'renren', 'text' => '人人'),
			array('v' => 'yoka', 'text' => 'Yoka'),
			//array('v' => 'myspace', 'text' => 'MySpace'),
		);

		$data = $this->Product->searchDaoguiCaptcha($data_total, $product_kw, $status, $user_name, $code, $time_type, $start_time, $end_time, $page, $per_page, $platform);
		$this->set('data', $data);
		$this->set('data_total', $data_total);

		// download excel
		if ($download){
			$xls = new Excel_XML('UTF-8', false, 'Apply'.$platform);
			$xls->addArray(array(array(
				'中奖时间',
				'姓名',
				'用户名',
				'生日',
				'电话号码',
				'省份',
				'城市',
				'地址',
				'邮编',
				'验证码',
				'状态',
				)));
			foreach ($data as $r){
				$xls->addArray(array(array(
					$r['create_time'],
					$r['user_name'],
					$r['ht_user_name'],
					$r['birthday'],
					$r['phone'],
					$r['province'],
					$r['city'],
					$r['address'],
					$r['zipcode'],
					$r['code'],
					$r['status'],
				)));
			}
			$xls->generateXML('Apply'.$platform);
			exit;
		}
 
		 
		$this->set('total_page', ceil($data_total/$per_page));
		$this->set('url_prefix', $this->make_page_url_prefix('http://'.$_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'])); 
		$this->set('page', $page);

		$this->set('product_kw', $product_kw);
		$this->set('status', $status);
		$this->set('user_name', $user_name);
		$this->set('code' , $code);
		$this->set('time_type', $time_type);
		$this->set('start_time', $start_time);
		$this->set('end_time', $end_time);
		$this->set('status_select', $status_select);
		$this->set('time_type_select', $time_type_select);
		$this->set('platform', $platform);
		$this->set('platform_select', $platform_select);
		
		$this->render('/product/captcha');
	}/*}}}*/

	function make_page_url_prefix($url_prefix){/*{{{*/
		$url_prefix = preg_replace('/\bpage=\d&?(.*)/', '\1', $url_prefix, -1, $replace_count);
		if (strpos($url_prefix, '?') !== false){
			$url_prefix .= '&page=';
		} else {
			$url_prefix .= '?page=';
		}

		return $url_prefix;
	}/*}}}*/

	function getOrcheckCaptchaUrl($product_kw, $token=null){/*{{{*/
		$secret_key = 'asf6812$^$#$;lc;';
		$ok_token = md5($secret_key.$product_kw);

		$product_kw = urlencode($product_kw);

		if (empty($token)){ // Get
			return "http://{$_SERVER['HTTP_HOST']}/tryapp/TryAppManagement/index.php/product/captcha/{$ok_token}?product_kw={$product_kw}";
		} else { // Check
			return ($ok_token == $token);
		}
	}/*}}}*/

	function getSmallCaptchaUrl($store){/*{{{*/
		$secret_key = 'sf6556#$#l';
		$ok_token = md5($secret_key.$store);
		return "http://{$_SERVER['HTTP_HOST']}/product/checkCaptcha/{$store}/{$ok_token}/";
	}/*}}}*/
}

//兑换物品后提示：感谢您一直以来的支持，请与我们的管理员联系 http://renren.com/profile.do?id=298825783&_vip_flag=77，请把您的姓名、联系方式、邮递地址发站内信。物品快递后将有专人与您联系！谢谢！欢迎继续申请更多机会！
